﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web;
using System.IO;
using Tsanie.DmPoster.Utils;

namespace Tsanie.DmPoster {
    public partial class LoginForm : Form {
        private string _cookie = null;
        private bool _logined = false;

        private LoginForm() {
            InitializeComponent();
        }
        public static bool ShowLogin(Form owner) {
            LoginForm form = new LoginForm();
            form.ShowDialog(owner);
            return form._logined;
        }

        private void buttonCancel_Click(object sender, EventArgs e) {
            this.Close();
        }
        private void buttonLogin_Click(object sender, EventArgs e) {
            byte[] bs = Encoding.ASCII.GetBytes("fmdo=login&dopost=login&gourl=&keeptime=604800&userid="
                + HttpUtility.UrlEncode(textUserId.Text, Encoding.UTF8) + "&pwd="
                + HttpUtility.UrlEncode(textPwd.Text, Encoding.UTF8) + "&vdcode="
                + HttpUtility.UrlEncode(textVdCode.Text, Encoding.UTF8));
            Http.Connect(Config.m_HttpBase + "/member/index_do.php", (request) => {
                request.Method = "POST";
                request.Headers["Cookie"] = _cookie;
                request.Referer = Config.m_HttpBase + "/member/";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = bs.Length;
                using (Stream loginStream = request.GetRequestStream()) {
                    loginStream.Write(bs, 0, bs.Length);
                    loginStream.Close();
                }
                Application.DoEvents();
            }, (request, response) => {
                string cookies = "";
                foreach (string cookie in response.Headers["Set-Cookie"].Split(new char[] { ';', ',' })) {
                    string[] kv = cookie.Trim().Split('=');
                    if (kv[0].StartsWith("Dede") && kv[1] != "deleted") {
                        cookies += cookie.Trim() + "; ";
                    }
                }
                if (string.IsNullOrEmpty(cookies)) {
                    using (Stream stream = response.GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        string str = null;
                        while ((str = reader.ReadLine()) != null) {
                            if (str.StartsWith("document.write(\"") && str[16] != '<') {
                                MessageBox.Show(this,
                                    str.Substring(16, str.IndexOf('\"', 16) - 16),
                                    "登录", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                break;
                            }
                        }
                        reader.Close();
                        reader.Dispose();
                    }
                    textVdCode.Text = "";
                    textUserId.Focus();
                    textUserId.SelectAll();
                } else {
                    Config.m_Cookie = cookies;
                    _logined = true;
                    if (checkAutoLogin.Checked) {
                        Config.SetValue("Cookie", cookies);
                    }
                    this.Close();
                }
            }, (ex) => {
                MessageBox.Show(this, "登录失败：" + ex.Message, "登录", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textVdCode.Text = "";
            });
        }

        private void pictureVdcode_Click(object sender, EventArgs e) {
            GetVdCode();
        }
        private void GetVdCode() {
            bool retry;
            do {
                retry = false;
                Http.Connect(Config.m_HttpBase + "/include/vdimgck.php?r=" + Utility.Rnd.NextDouble(), (request) => {
                    request.Accept = "image/png,image/*;q=0.8,*/*;q=0.5";
                    request.Referer = Config.m_HttpBase + "/login.php";
                }, (request, response) => {
                    if (response.StatusCode == HttpStatusCode.OK) {
                        using (Stream stream = response.GetResponseStream()) {
                            pictureVdcode.Image = Bitmap.FromStream(stream);
                            stream.Close();
                            stream.Dispose();
                        }
                        _cookie = response.Headers["Set-Cookie"];
                        if (string.IsNullOrEmpty(_cookie)) {
                            MessageBox.Show(this, "获取验证码session失败！", "验证码",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }, (ex) => {
                    if (MessageBox.Show(this, "连接失败！是否重试？\n（" + ex.Message + "）", "验证码",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                        == System.Windows.Forms.DialogResult.Yes) {
                        retry = true;
                    }
                });
            } while (retry);
        }
        private void textVdCode_Enter(object sender, EventArgs e) {
            GetVdCode();
        }
    }
}
